<template>
	<div class="dashboard-container flex flex-column">
		<div class="dashboard-header flex align-center">
			<img src="@/static/桂林人民LOGO.png" class="logo">
			<div class="title-box flex-auto" @click="jump" style="cursor: pointer">
				<div class="title">医疗质量与安全维度(核心使命)</div>
				<div class="hospital-name">桂林市人民医院</div>
			</div>
			<div class="right-box flex align-center">
				<!--         <div style="margin-right: 20px;">-->
				<!--           <screenfull id="screenfull" class="right-menu-item hover-effect" />-->
				<!--         </div>-->
				<div class="time-box">
					<div class="current-time-label">当前时间</div>
					<div class="current-time-value">{{currentTime}}</div>
				</div>
				<div  @click="drawer = true" style="cursor: pointer">
					<img src="@/static/角色图标.png" class="avatar">
					<div class="user-name">人云医疗智能体</div>
				</div>

			</div>
		</div>
		<div class="dashboard-main flex justify-content-space-between flex-auto" style="gap: 20px">
			<div class="left-wrapper flex-auto  flex flex-column" ref="leftWrapper">
				<!--  第一排图表     -->
				<div class="flex flex-auto" style="gap: 15px;">
					<ECharts :options="mortalityRateChartOptions.echarts" class="flex-auto"
						style="height: 100%;position: relative">
						<div style="position: absolute;right: 20px;top: 10px;font-size: 14px">
							<span style="color: #2C58A5;">{{mortalityRateChartOptions.data.today_LowDeathRatio}}%</span>
							<span v-if="mortalityRateChartOptions.data.lowDeathRatio>0" style="color: #20B558;padding-left: 10px;">环比
								↑ {{mortalityRateChartOptions.data.lowDeathRatio}} %</span>
							<span v-else-if="mortalityRateChartOptions.data.lowDeathRatio==0"
								style="color: #c9bcbc;padding-left: 10px;">环比 {{mortalityRateChartOptions.data.lowDeathRatio}} %</span>
							<span v-else style="color: #D23E40;padding-left: 10px;">环比
								↓{{mortalityRateChartOptions.data.lowDeathRatio}} %</span>
						</div>
					</ECharts>
					<ECharts :options="surgeryComplicationRateChartOptions.echarts" class="flex-auto" style="height: 100%;">
						<div style="position: absolute;right: 20px;top: 10px;font-size: 14px">
							<span style="color: #2C58A5;">{{surgeryComplicationRateChartOptions.data.today_SurgicalRatio}}%</span>
							<span v-if="surgeryComplicationRateChartOptions.data.surgicalRatio>0"
								style="color: #20B558;padding-left: 10px;">环比 ↑
								{{surgeryComplicationRateChartOptions.data.surgicalRatio}} %</span>
							<span v-else-if="surgeryComplicationRateChartOptions.data.surgicalRatio==0"
								style="color: #c9bcbc;padding-left: 10px;">环比 {{surgeryComplicationRateChartOptions.data.surgicalRatio}}
								%</span>
							<span v-else style="color: #D23E40;padding-left: 10px;">环比
								↓{{surgeryComplicationRateChartOptions.data.surgicalRatio}} %</span>
						</div>
					</ECharts>
					<ECharts :options="infectionRateChartOptions.echarts" class="flex-auto" style="height: 100%;">
						<div style="position: absolute;right: 20px;top: 10px;font-size: 14px">
							<span style="color: #2C58A5;">{{infectionRateChartOptions.data.today_ISurgicalRatio}}%</span>
							<span v-if="infectionRateChartOptions.data.iSurgicalRatio>0" style="color: #20B558;padding-left: 10px;">环比
								↑ {{infectionRateChartOptions.data.iSurgicalRatio}} %</span>
							<span v-else-if="infectionRateChartOptions.data.iSurgicalRatio==0"
								style="color: #c9bcbc;padding-left: 10px;">环比 {{infectionRateChartOptions.data.iSurgicalRatio}} %</span>
							<span v-else style="color: #D23E40;padding-left: 10px;">环比
								↓{{infectionRateChartOptions.data.iSurgicalRatio}} %</span>
						</div>
					</ECharts>
				</div>
				<!--  第二排图表      -->
				<div style="margin-top:10px;gap: 20px;" class="flex justify-content-space-between flex-auto">
					<div class="flex flex-auto" style="gap: 20px;height: 100%">
						<ECharts :options="averageLengthOfStayChartOptions.echarts" style="flex: 1;height: 100%;position: relative">
							<div style="position: absolute;right: 20px;top: 10px;font-size: 14px">
								<span style="color: #2C58A5;">{{averageLengthOfStayChartOptions.data.today_AvgPatientDayRatio}}</span>
								<span v-if="averageLengthOfStayChartOptions.data.avgPatientDayRatio>0"
									style="color: #20B558;padding-left: 10px;">环比 ↑
									{{averageLengthOfStayChartOptions.data.avgPatientDayRatio}} %</span>
								<span v-else-if="averageLengthOfStayChartOptions.data.avgPatientDayRatio==0"
									style="color: #c9bcbc;padding-left: 10px;">环比
									{{averageLengthOfStayChartOptions.data.avgPatientDayRatio}} %</span>
								<span v-else style="color: #D23E40;padding-left: 10px;">环比
									↓{{averageLengthOfStayChartOptions.data.avgPatientDayRatio}} %</span>
							</div>
						</ECharts>
						<ECharts :options="readmissionRateChartOptions.echarts" style="flex: 1;height: 100%;">
							<div style="position: absolute;right: 20px;top: 10px;font-size: 14px">
								<span style="color: #2C58A5;">{{readmissionRateChartOptions.data.today_RestartRatio}}</span>
								<span v-if="readmissionRateChartOptions.data.restartRatio>0"
									style="color: #20B558;padding-left: 10px;">环比 ↑ {{readmissionRateChartOptions.data.restartRatio}}
									%</span>
								<span v-else-if="readmissionRateChartOptions.data.restartRatio==0"
									style="color: #c9bcbc;padding-left: 10px;">环比 {{readmissionRateChartOptions.data.restartRatio}}
									%</span>
								<span v-else style="color: #D23E40;padding-left: 10px;">环比
									↓{{readmissionRateChartOptions.data.restartRatio}} %</span>
							</div>
						</ECharts>
					</div>
					<div class="flex flex-auto" style="height: 100%">
						<ECharts :options="clinicalPathwayRateChartOptions.echarts" style="flex: 2;height: 100%;">
							<div style="position: absolute;right: 20px;top: 10px;font-size: 14px">
								<span style="color: #2C58A5;">{{clinicalPathwayRateChartOptions.data.today_ClinicalPathwayRatio}}</span>
								<span v-if="clinicalPathwayRateChartOptions.data.clinicalPathwayRatio>0"
									style="color: #20B558;padding-left: 10px;">环比 ↑
									{{clinicalPathwayRateChartOptions.data.clinicalPathwayRatio}} %</span>
								<span v-else-if="clinicalPathwayRateChartOptions.data.clinicalPathwayRatio==0"
									style="color: #c9bcbc;padding-left: 10px;">环比
									{{clinicalPathwayRateChartOptions.data.clinicalPathwayRatio}} %</span>
								<span v-else style="color: #D23E40;padding-left: 10px;">环比
									↓{{clinicalPathwayRateChartOptions.data.clinicalPathwayRatio}} %</span>
							</div>
						</ECharts>
					</div>
				</div>
				<!--  第三排图表  -->
				<div style="margin-top: 10px;gap: 20px;" class="flex flex-auto">
					<div class="flex flex-auto" style="height: 100%">
						<ECharts :options="antibioticUsageIntensityChartOptions.echarts" style="flex: 2;height: 100%;">
							<div style="position: absolute;right: 20px;top: 10px;font-size: 14px">
								<span
									style="color: #2C58A5;">{{antibioticUsageIntensityChartOptions.data.today_ANTDrugTakeRatio}}</span>
								<span v-if="antibioticUsageIntensityChartOptions.data.antDrugTakeRatio>0"
									style="color: #20B558;padding-left: 10px;">环比 ↑
									{{antibioticUsageIntensityChartOptions.data.antDrugTakeRatio}} %</span>
								<span v-else-if="antibioticUsageIntensityChartOptions.data.antDrugTakeRatio==0"
									style="color: #c9bcbc;padding-left: 10px;">环比
									{{antibioticUsageIntensityChartOptions.data.antDrugTakeRatio}} %</span>
								<span v-else style="color: #D23E40;padding-left: 10px;">环比
									↓{{antibioticUsageIntensityChartOptions.data.antDrugTakeRatio}} %</span>
							</div>
						</ECharts>
					</div>
					<div class="flex flex-auto" style="gap: 20px;height: 100%">
						<ECharts :options="criticalValueResponseRateChartOptions.echarts"
							style="flex: 1;height: 100%;position: relative">
							<div style="position: absolute;right: 20px;top: 10px;font-size: 14px">
								<span style="color: #2C58A5;">{{criticalValueResponseRateChartOptions.data.today_ReportRatio}}</span>
								<span v-if="criticalValueResponseRateChartOptions.data.reportRatio>0"
									style="color: #20B558;padding-left: 10px;">环比 ↑
									{{criticalValueResponseRateChartOptions.data.reportRatio}} %</span>
								<span v-else-if="criticalValueResponseRateChartOptions.data.reportRatio==0"
									style="color: #c9bcbc;padding-left: 10px;">环比
									{{criticalValueResponseRateChartOptions.data.reportRatio}} %</span>
								<span v-else style="color: #D23E40;padding-left: 10px;">环比
									↓{{criticalValueResponseRateChartOptions.data.reportRatio}} %</span>
							</div>
						</ECharts>
						<ECharts :options="largeEquipmentPositiveRateChartOptions.echarts" style="flex: 1;height: 100%;">
							<div style="position: absolute;right: 20px;top: 10px;font-size: 14px">
								<span style="color: #2C58A5;">{{largeEquipmentPositiveRateChartOptions.data.today_POSSumRatio}}</span>
								<span v-if="largeEquipmentPositiveRateChartOptions.data.posSumRatio>0"
									style="color: #20B558;padding-left: 10px;">环比 ↑
									{{largeEquipmentPositiveRateChartOptions.data.posSumRatio}} %</span>
								<span v-else-if="largeEquipmentPositiveRateChartOptions.data.posSumRatio==0"
									style="color: #c9bcbc;padding-left: 10px;">环比
									{{largeEquipmentPositiveRateChartOptions.data.posSumRatio}} %</span>
								<span v-else style="color: #D23E40;padding-left: 10px;">环比
									↓{{largeEquipmentPositiveRateChartOptions.data.posSumRatio}} %</span>
							</div>
						</ECharts>
					</div>
				</div>
				<!--  第四排信息 -->
				<div style="margin-top: 10px; background-color: #1E293B;border-radius: 10px;padding: 20px;height: fit-content;">
					<div class="flex align-center">
						<img style="width: 30px;height: 20px;margin-right: 10px;" src="@/static/1其它医疗质量.png" alt="">
						<div style="font-weight: bolder;font-size: 18px;">其他医疗质量与安全指标</div>
					</div>
					<div class="indicator-container " style="height: 140px">
						<div v-for="(item, index) in indicators" :key="index" class="indicator-item">
							<img :src="item.icon" class="indicator-icon " />
							<div class="indicator-content">
								<div class="indicator-title">{{ item.title }}</div>
								<div class="indicator-rate">
									<span class="current-rate">当前发生率:{{ item.currentRate }}</span>
									<span :class="['change', item.trend === 'up' ? 'up' : 'down']">环比 {{ item.change }}</span>
								</div>
								<div class="indicator-desc">{{ item.description }}</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="right-wrapper flex flex-column" style="width: 370px">
				<!-- 实时预警 -->
				<div class=" alert-section  flex flex-column" style="margin-top: 10px">
					<div class="section-header flex align-center">
						<img src='@/static/实时预警.png' style="height: 20px;margin-right: 10px;" alt="">
						<span class="title"
							style="font-size: 18px;font-weight:400;letter-spacing: 1px;font-weight: bolder">医疗质量实时预警</span>
					</div>
					<div style="overflow-y: scroll;height: 890px;margin-top:10px;">
						<div :style="{ backgroundColor: item.bgColor, borderLeft: `4px solid ${item.borderLeftColor}`}"
							v-for="(item, index) in alerts" :key="index" class="alert-item high-risk">
							<div class="alert-title">{{ item.title }}</div>
							<div class="alert-time">{{ item.time }}</div>
							<div class="alert-content" v-html="item.content"></div>
						</div>
					</div>
				</div>

			</div>
		</div>
		<!-- 抽屉效果 -->
		<el-drawer v-model="drawer" :modal="true" size="800px" height="100vh" title="I am the title" class="custom-drawer"
			:with-header="false" @opened="opened">
			<div class="flex flex-column" style="height: 100%;padding: 20px;background-color: #ffffff">
				<div class="flex flex-column"
					style="background-color: #ffffff;color: #333333;font-size: 22px;font-weight: bolder">人云联拓·医疗智能体解决方案</div>
				<div v-if="isAiLoading" ref="outputRef" class="response-box flex-auto">
					<div class="ai-response-content" v-html="renderedHTML"></div>
					<span v-if="isStreaming" class="cursor">|</span>
				</div>
				<div v-else class="flex-auto flex flex-column align-center justify-content-center">
					<aiLoading></aiLoading>
				</div>
			</div>
		</el-drawer>
		<!---->
	</div>
</template>
<script setup>
	import {
		ref,
		onUnmounted,
		onMounted,
		nextTick
	} from 'vue'
	import ECharts from '@/components/ECharts.vue'
	import Screenfull from '@/components/Screenfull'
	import aiLoading from '@/components/aiLoading/index.vue';
	import {
		useCurrentTime
	} from '@/hooks/useCurrentTime'
	const {
		currentTime
	} = useCurrentTime()
	// 导入全屏工具
	import {
		fullscreenUtils
	} from '@/utils/fullscreen.js'
	import {
		getDisplayANTDrug,
		getDisplayAVGPerson,
		getDisplayClinical,
		getDisplayDevice,
		getDisplayISurgical,
		getDisplayLowDeath,
		getDisplayQuality,
		getDisplayRelapse,
		getDisplayReport,
		getDisplayRestart
	} from "@/api/quality/safety.js";
	const isAiLoading = ref(false);
	import {
		useRouter
	} from 'vue-router'
	import MarkdownIt from "markdown-it/index.mjs";
	import DOMPurify from "dompurify";
	const router = useRouter()
	const jump = () => {
    router.push({path:"/NavPage"})
	}

	// 全屏切换函数 - 可以在模板中直接调用
	const toggleFullscreen = () => {
		fullscreenUtils.toggleFullscreen()
	}
	// 检查当前是否全屏的函数
	const checkFullscreenStatus = () => {
		return fullscreenUtils.isFullscreen()
	}



	// 获取元素引用
	const leftWrapper = ref(null);
	const scrollContainer = ref(null);
	const indicators = ref([{
			icon: new URL('@/static/1不良事件.png', import.meta.url).href,
			title: '全院医疗质量与安全不良事件 (AE) 发生率',
			currentRate: '2.8%',
			change: '-0.5%',
			trend: 'down', // 'up' 或 'down'
			description: '较上月下降0.5%，但仍需持续关注用药安全和跌倒预防。'
		},
		{
			icon: new URL('@/static/1HAI感染.png', import.meta.url).href,
			title: '全院医院感染 (HAI) 发生率',
			currentRate: '1.5%',
			change: '+0.3%',
			trend: 'up',
			description: '较上月上升0.3%，重点加强ICU和外科手卫生监管。'
		},
		{
			icon: new URL('@/static/1住院患者.png', import.meta.url).href,
			title: '全院住院患者死亡率',
			currentRate: '0.9%',
			change: '-0.2%',
			trend: 'down',
			description: '较上月下降0.2%，继续保持危重患者早期预警系统运行。'
		}
	]);
	const alerts = ref([{
			type: 'warning',
			title: '高风险手术',
			time: '14:28',
			content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
			icon: '⚠️',
			bgColor: '#2D2E32',
			borderLeftColor: '#FD6A6A',
		},
		{
			type: 'danger',
			title: '危重患者',
			time: '14:25',
			content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
			icon: '🚨',
			bgColor: '#2D3530',
			borderLeftColor: '#FFB156',
		},
		{
			type: 'warning',
			title: '高风险手术',
			time: '14:28',
			content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
			icon: '⚠️',
			bgColor: '#2D3530',
			borderLeftColor: '#FFB156'
		},
		{
			type: 'danger',
			title: '危重患者',
			time: '14:25',
			content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
			icon: '🚨',
			bgColor: '#2D3530',
			borderLeftColor: '#FFB156'
		},
		{
			type: 'warning',
			title: '高风险手术',
			time: '14:28',
			content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
			icon: '⚠️',
			bgColor: '#2D3530',
			borderLeftColor: '#FFB156'
		},
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D2E32',
      borderLeftColor: '#FD6A6A',
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156',
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },{
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D2E32',
      borderLeftColor: '#FD6A6A',
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156',
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },{
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D2E32',
      borderLeftColor: '#FD6A6A',
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156',
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },{
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D2E32',
      borderLeftColor: '#FD6A6A',
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156',
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },{
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D2E32',
      borderLeftColor: '#FD6A6A',
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156',
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },{
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D2E32',
      borderLeftColor: '#FD6A6A',
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156',
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },{
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D2E32',
      borderLeftColor: '#FD6A6A',
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156',
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'danger',
      title: '危重患者',
      time: '14:25',
      content: '患者: 李娜(68岁)<br>ICU脓毒症休克 APACHE II评分28',
      icon: '🚨',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    },
    {
      type: 'warning',
      title: '高风险手术',
      time: '14:28',
      content: '患者: 张伟(45岁)<br>心脏搭桥手术(ASA分级IV级)',
      icon: '⚠️',
      bgColor: '#2D3530',
      borderLeftColor: '#FFB156'
    }
	]);
	const qualityTargets = ref([{
			label: '抗菌药物使用强度',
			value: '45.2/40 DDds',
			progress: 85,
			target: '40 DDds',
			color: '#f56c6c'
		},
		{
			label: 'I类切口预防用药',
			value: '18%/20%',
			progress: 90,
			target: '20%',
			color: '#409eff'
		},
		{
			label: '平均住院日',
			value: '7.2/7.5天',
			progress: 96,
			target: '7.5天',
			color: '#12ec2f'
		},
		{
			label: '抗菌药物使用强度',
			value: '45.2/40 DDds',
			progress: 85,
			target: '40 DDds',
			color: '#f56c6c'
		},
		{
			label: 'I类切口预防用药',
			value: '18%/20%',
			progress: 90,
			target: '20%',
			color: '#409eff'
		},
		{
			label: '平均住院日',
			value: '7.2/7.5天',
			progress: 96,
			target: '7.5天',
			color: '#12ec2f'
		}
	]);
	const aiSuggestions = ref([{
			title: '根因分析',
			bgColor: '#133538',
			borderLeftColor: '#00B5AD',
			desc: '监测到AI分析口术感染率环比上升15%，AI初步分析主要与骨科某病区的术前预防性抗菌药物使用时机有关(30%病例未在术前0.5-1小时内给药)。',
			suggestion: '建议: 立即对该病区进行专项督查，并加强手术室环节培训。'
		},
		{
			title: '优化建议',
			bgColor: '#133538',
			borderLeftColor: '#00B5AD',
			desc: '"UF39 呼吸系统感染/炎症" DRG组，我院平均住院日比区域标杆长1.2天，但费用持平。',
			suggestion: '建议: 分析临床路径，优化检验检查和给药流程，缩短住院日可提升床位周转率和收益。'
		},
		{
			title: '预测性预警',
			bgColor: '#2D3530',
			borderLeftColor: '#FDB055',
			desc: '根据近期病历质控评分下降趋势，预测下月DRG小组错误率有上升风险。',
			suggestion: '建议: 提前对编码员和临床医师进行针对性培训。'
		},
		{
			title: '根因分析',
			bgColor: '#2D3530',
			borderLeftColor: '#FDB055',
			desc: '监测到AI分析口术感染率环比上升15%，AI初步分析主要与骨科某病区的术前预防性抗菌药物使用时机有关(30%病例未在术前0.5-1小时内给药)。',
			suggestion: '建议: 立即对该病区进行专项督查，并加强手术室环节培训。'
		}
	]);
	// 低风险患者死亡比例趋势
	const mortalityRateChartOptions = ref({
		data: {
			lowDeathRatio: null,
			today_LowDeathRatio: null
		},
		echarts: {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				},
				formatter: (params) => {
					const value = params[0].value;
					return `${params[0].axisValue}月<br/>死亡率: ${value}%`;
				}
			},
			title: [{
					text: '低风险患者死亡比例趋势',
					left: 20,
					top: 10,
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				{
					text: '评估低风险患者群体中的死亡比例，反映基础医疗质量',
					left: 20,
					top: 35,
					textStyle: {
						color: '#ccc',
						fontSize: 12,
						fontWeight: 'normal'
					}
				}
			],
			xAxis: {
				type: 'category',
				axisLabel: {
					color: '#ccc',
					fontSize: 12,
					rotate: 0
				},
				data: ['1月', '2月', '3月', '4月', '5月', '6月'],
			},
			yAxis: {
				type: 'value',
				min: 0,
				splitLine: {
					show: false
				},
				axisLabel: {
					color: '#ccc',
					fontSize: 12,
					rotate: 0,
					formatter: '{value}%' // 添加这一行来显示百分号
				},
			},
			series: [{
				name: '死亡比例',
				type: 'line',
				smooth: true, // 平滑曲线
				symbolSize: 4,
				lineStyle: {
					color: '#3676DE',
					width: 1
				},
				areaStyle: {
					color: {
						type: 'linear',
						x: 0, // 起始点 x 坐标（0-1 范围，相对于图表容器）
						y: 0, // 起始点 y 坐标
						x2: 0, // 结束点 x 坐标
						y2: 1, // 结束点 y 坐标（0 到 1 表示从顶部到底部）
						colorStops: [{
								offset: 0,
								color: 'rgba(64, 158, 254, 0.8)'
							}, // 起点：半透明
							{
								offset: 1,
								color: 'rgba(64, 158, 254, 0)'
							} // 终点：完全透明
						]
					}
				},
				data: [1.2, 1.0, 0.8, 0.7, 0.5, 0.6]
			}],
			grid: {
				left: '10%',
				top: '25%',
				bottom: '15%'
			},
		}
	});
	// 手术患者并发症发生率
	const surgeryComplicationRateChartOptions = ref({
		data: {
			today_SurgicalRatio: null,
			surgicalRatio: null
		},
		echarts: {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				},
				formatter: (params) => {
					const value = params[0].value;
					return `${params[0].axisValue}<br/>并发症发生率: ${value}%`;
				}
			},
			title: [{
					text: '手术患者并发症发生率',
					left: 20,
					top: 10,
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				{
					text: '统计术后出现并发症的患者比例，衡量手术安全性',
					left: 20,
					top: 35,
					textStyle: {
						color: '#ccc',
						fontSize: 12,
						fontWeight: 'normal'
					}
				}
			],
			xAxis: {
				type: 'category',
				data: ['普外科', '骨科', '心内科', '胸外科', '神经内科'],
				axisLabel: {
					color: '#ccc',
					fontSize: 12,
					rotate: 0
				},
				axisLine: {
					lineStyle: {
						color: '#818999'
					}
				}
			},
			yAxis: {
				type: 'value',
				interval: 20,
				axisLabel: {
					color: '#ccc',
					fontSize: 12,
					formatter: '{value}%'
				},
				splitLine: {
					show: false // 隐藏Y轴横线
				},
				axisLine: {
					lineStyle: {
						color: '#818999'
					}
				}
			},
			series: [{
				name: '并发症发生率',
				type: 'bar',
				barWidth: '50%',
				itemStyle: {
					color: function(params) {
						return {
							type: 'linear',
							x: 0,
							y: 0,
							x2: 0,
							y2: 1,
							colorStops: [{
									offset: 0,
									color: "#EF4545"
								},
								{
									offset: 1,
									color: "rgba(238,68,68,0.24)"
								}
							]
						};
					}
				},
				data: [4.2, 3.8, 3.5, 2.9, 3.2]
			}],
			grid: {
				left: '10%',
				top: '25%',
				bottom: '10%'
			},
			backgroundColor: 'transparent'
		}
	});
	// I类切口手术部位感染率
	const infectionRateChartOptions = ref({
		data: {
			today_ISurgicalRatio: null,
			iSurgicalRatio: null,
		},
		echarts: {
			tooltip: {
				trigger: 'item',
				formatter: '{a} <br/>{b}: {c} ({d}%)'
			},
			title: [{
					text: 'I类切口手术部位感染率',
					left: 20,
					top: 10,
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				{
					text: '清洁手术切口感染情况，反映手术室无菌管理水平',
					left: 20,
					top: 35,
					textStyle: {
						color: '#ccc',
						fontSize: 12,
						fontWeight: 'normal'
					}
				}
			],
			legend: {
				show: true,
				orient: 'vertical',
				right: 20,
				top: 'middle',
				textStyle: {
					color: '#ccc'
				},
				data: ['切口感染', '正常']
			},
			series: [{
				name: 'I类切口手术部位感染率',
				type: 'pie',
				radius: ['35%', '50%'], // 内外半径，形成环形
				avoidLabelOverlap: true,
				label: {
					show: false
				},
				labelLine: {
					show: false
				},
				data: [{
						value: 1.2, // 感染率
						name: '切口感染',
						itemStyle: {
							color: '#EF4545' // 红色
						}
					},
					{
						value: 98.8, // 正常比例（100 - 1.2）
						name: '正常',
						itemStyle: {
							color: '#10B981' // 绿色
						}
					}
				],
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					}
				}
			}],
			grid: {
				left: '10%',
				top: '25%',
				bottom: '15%'
			}
		}
	});
	//平均住院日
	const averageLengthOfStayChartOptions = ref({
		data: {
			avgPatientDayRatio: null,
			today_AvgPatientDayRatio: null
		},
		echarts: {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				},
				formatter: (params) => {
					return `${params[0].value}天`;
				}
			},
			title: [{
					text: '平均住院日',
					left: 20,
					top: 10,
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				{
					text: '患者平均住院时长，反映医疗效率和资源利用',
					left: 20,
					top: 35,
					textStyle: {
						color: '#ccc',
						fontSize: 12,
						fontWeight: 'normal'
					}
				}
			],
			series: [{
				name: '平均住院日',
				type: 'gauge',
				radius: '75%',
				center: ['50%', '60%'],
				min: 0,
				splitNumber: 10,
				axisLine: {
					lineStyle: {
						width: 10,
						color: [
							[0.2, '#EF4545'], // 5~6 红色
							[0.4, '#F59E0B'], // 6~7 橙色
							[0.6, '#FBBF24'], // 7~8 黄色
							[0.8, '#10B981'], // 8~9 绿色
							[1.0, '#059669'] // 9~10 深绿
						]
					}
				},
				axisTick: {
					splitNumber: 10,
					length: 8,
					lineStyle: {
						color: '#818999'
					}
				},
				axisLabel: {
					color: '#fff',
					fontSize: 12,
					formatter: '{value}'
				},
				detail: {
					valueAnimation: true,
					formatter: '{value}天',
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				data: [{
					value: 6.8,
					name: '平均住院日'
				}]
			}],
			grid: {
				left: '10%',
				top: '25%',
				bottom: '15%'
			}
		}
	});
	// 重返率
	const readmissionRateChartOptions = ref({
		data: {
			restartRatio: null,
			today_RestartRatio: null
		},
		echarts: {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				},
				formatter: (params) => {
					const value = params[0].value;
					return `${params[0].axisValue}<br/>重返率: ${value}%`;
				}
			},
			title: [{
					text: '重返率',
					left: 20,
					top: 10,
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				{
					text: '出院后短期内再次入院比例，评估诊疗质量和出院标准',
					left: 20,
					top: 35,
					textStyle: {
						color: '#ccc',
						fontSize: 12,
						fontWeight: 'normal'
					}
				}
			],
			xAxis: {
				type: 'category',
				data: ['1月', '2月', '3月', '4月', '5月', '6月'],
				axisLabel: {
					color: '#ccc',
					fontSize: 12,
					rotate: 0
				},
				axisLine: {
					lineStyle: {
						color: '#818999'
					}
				}
			},
			yAxis: {
				type: 'value',
				min: 0,
				axisLabel: {
					color: '#ccc',
					fontSize: 12,
					formatter: '{value}%'
				},
				splitLine: {
					show: false // 隐藏Y轴横线
				},
				axisLine: {
					lineStyle: {
						color: '#818999'
					}
				}
			},
			series: [{
				name: '重返率',
				type: 'line',
				smooth: true, // 平滑曲线
				symbolSize: 4,
				lineStyle: {
					color: '#EF4545',
					width: 1
				},
				itemStyle: {
					color: '#EF4545' // 显式设置数据点颜色为红色
				},
				areaStyle: {
					color: {
						type: 'linear',
						x: 0,
						y: 0,
						x2: 0,
						y2: 1,
						colorStops: [{
								offset: 0,
								color: 'rgba(239, 69, 69, 0.8)'
							},
							{
								offset: 1,
								color: 'rgba(239, 69, 69, 0)'
							}
						]
					}
				},
				data: [1.8, 1.9, 2.0, 2.1, 2.2, 2.1]
			}],
			grid: {
				left: '17%',
				top: '25%',
				bottom: '15%'
			}
		}
	});
	//出院患者手术占比
	const clinicalPathwayRateChartOptions = ref({
		data: {
			clinicalPathwayRatio: 0,
			today_ClinicalPathwayRatio: 13
		},
		echarts: {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'shadow'
				},
				formatter: (params) => {
					const value = params[0].value;
					return `${params[0].axisValue}<br/>出院患者手术占比: ${value}%`;
				}
			},
			title: [{
					text: '出院患者手术占比',
					left: 20,
					top: 10,
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				{
					text: '出院患者中接受手术治疗的比例,反映医院手术能力和专科特色',
					left: 20,
					top: 35,
					textStyle: {
						color: '#ccc',
						fontSize: 12,
						fontWeight: 'normal'
					}
				}
			],
			xAxis: {
				type: 'category',
				data: ['普外科', '骨科', '心内科', '胸外科', '神经内科'],
				axisLabel: {
					color: '#ccc',
					fontSize: 12,
					rotate: 0
				},
				axisLine: {
					lineStyle: {
						color: '#818999'
					}
				}
			},
			yAxis: {
				type: 'value',
				min: 0,
				interval: 1,
				axisLabel: {
					color: '#ccc',
					fontSize: 12,
					formatter: '{value}%'
				},
				splitLine: {
					show: false // 隐藏Y轴横线
				},
				axisLine: {
					lineStyle: {
						color: '#818999'
					}
				}
			},
			series: [{
				name: '并发症发生率',
				type: 'bar',
				barWidth: '50%',
				itemStyle: {
					color: function(params) {
						return {
							type: 'linear',
							x: 0,
							y: 0,
							x2: 0,
							y2: 1,
							colorStops: [{
									offset: 0,
									color: "#6ea3f8"
								},
								{
									offset: 1,
									color: "#075ae2"
								},
							]
						};
					}
				},
				data: [4.2, 3.8, 3.5, 2.9, 3.2]
			}],
			grid: {
				left: '10%',
				top: '25%',
				bottom: '15%'
			},
			backgroundColor: 'transparent'
		}
	});
	//抗菌药物使用强度
	const antibioticUsageIntensityChartOptions = ref({
		data: {
			today_ANTDrugTakeRatio: null,
			antDrugTakeRatio: null,
		},
		echarts: {
			title: [{
					text: '抗菌药物使用强度',
					left: 20,
					top: 10,
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				{
					text: '抗菌药物消耗指标,反映合理用药和感染控制水平',
					left: 20,
					top: 35,
					textStyle: {
						color: '#ccc',
						fontSize: 12,
						fontWeight: 'normal'
					}
				}
			],
			tooltip: {
				show: true,
				formatter: function(params) {
					return `${params.seriesName}<br>${params.name} ${params.value}`;
				}
			},
			visualMap: {
				min: 0, // 最小值
				calculable: true, // 允许拖拽调整范围
				orient: 'horizontal', // 水平放置
				left: 'center', // 居中
				bottom: -15, // 距离底部的距离
				// 自定义颜色渐变
				color: [
					'#00B42A', // 绿色（低值）
					'#87CE00',
					'#FFD700', // 黄色
					'#FF7F00',
					'#FF4500', // 红色（高值）
				],
				textStyle: {
					color: '#fff'
				}
			},
			xAxis: {
				type: 'category',
				data: ['1月'],
				axisLabel: {
					color: '#ccc'
				},
				axisLine: {
					lineStyle: {
						color: 'rgba(255,255,255,0.2)'
					}
				}
			},
			yAxis: {
				type: 'category',
				data: ['儿科', '内科'],
				axisLabel: {
					color: '#ccc'
				},
				axisLine: {
					lineStyle: {
						color: 'rgba(255,255,255,0.2)'
					}
				}
			},
			series: [{
				name: '热力图数据',
				type: 'heatmap', // 图表类型为热力图
				data: [],
				label: {
					show: true,
					color: '#fff'
				},
				// 热力图样式配置
				itemStyle: {
					borderWidth: 1,
					borderColor: 'rgba(0,0,0,0.1)'
				}
			}],
			grid: {
				left: '20%',
				top: '25%',
				bottom: '15%'
			},
		}
	});
	//
	const criticalValueResponseRateChartOptions = ref({
		data: {
			reportRatio: "44",
			today_ReportRatio: "44"
		},
		echarts: {
			tooltip: {
				trigger: 'item',
				formatter: '{a} <br/>{b}: {c} ({d}%)'
			},
			title: [{
					text: '检验和病理阳性率',
					left: 20,
					top: 10,
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				{
					text: '实验室检验和病理检查中发现异常的比例，反映诊断准确性',
					left: 20,
					top: 35,
					textStyle: {
						color: '#ccc',
						fontSize: 12,
						fontWeight: 'normal'
					}
				}
			],
			series: [{
				name: '危急值报告及时处置率',
				type: 'pie',
				radius: ['35%', '55%'],
				avoidLabelOverlap: true,
				label: {
					show: true,
					position: 'center',
					formatter: '{a|{c}%}',
					rich: {
						a: {
							fontSize: 14,
							fontWeight: 'bold',
							color: '#fff'
						}
					}
				},
				labelLine: {
					show: false
				},
				data: [{
						value: 92,
						name: '及时处置',
						itemStyle: {
							color: {
								type: 'linear',
								x: 0,
								y: 0,
								x2: 1,
								y2: 0,
								colorStops: [{
										offset: 0,
										color: '#3B82F6'
									}, // 蓝色
									{
										offset: 1,
										color: '#10B981'
									} // 绿色
								]
							}
						}
					},
					{
						value: 8,
						name: '未及时处置',
						itemStyle: {
							color: '#1E293B' // 深灰（背景色）
						}
					}
				],
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					}
				}
			}],
			grid: {
				left: '10%',
				top: '25%',
				bottom: '15%'
			}
		}
	});
	//大型设备检查阳性率
	const largeEquipmentPositiveRateChartOptions = ref({
		data: {
			posSumRatio: 66.9,
			today_POSSumRatio: 66.1
		},
		echarts: {
			tooltip: {
				trigger: 'item',
				formatter: '{a} <br/>{b}: {c} ({d}%)'
			},
			title: [{
					text: '大型设备检查阳性率',
					left: 20,
					top: 10,
					textStyle: {
						color: '#fff',
						fontSize: 14,
						fontWeight: 'bold'
					}
				},
				{
					text: 'CT/MRI等检查发现异常的比例，评估检查适应症把握',
					left: 20,
					top: 35,
					textStyle: {
						color: '#ccc',
						fontSize: 12,
						fontWeight: 'normal'
					}
				}
			],
			legend: {
				show: true,
				orient: 'vertical',
				right: 20,
				top: 'middle',
				textStyle: {
					color: '#fff'
				},
				data: ['阳性', '阴性']
			},
			series: [{
				name: '大型设备检查阳性率',
				type: 'pie',
				radius: ['30%', '50%'],
				avoidLabelOverlap: true,
				label: {
					show: true
				},
				labelLine: {
					show: true
				},
				data: [{
						value: 66.9,
						name: '阳性',
						itemStyle: {
							color: '#FBBF24' // 橙色
						}
					},
					{
						value: 33.1,
						name: '阴性',
						itemStyle: {
							color: '#75b85e' // 深灰（背景色）
						}
					}
				],
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)'
					}
				}
			}],
			grid: {
				left: '10%',
				top: '25%',
				bottom: '15%'
			}
		}
	});
	//低风险患者死亡比例趋势 函数处理 ( √ )
	const mortalityRateChartOptionsFunDeal = (data) => {
		mortalityRateChartOptions.value.data = data.displayLowDeathRatioDto; // 环比数据等
		let x_data = [];
		let series_data = [];
		data.displayYearLowDeathRatioDtosList.forEach(item => {
			x_data.push(item.year + "年" + item.month + "月");
			series_data.push(item.lowDeathRatioCount);
		});
		nextTick(() => {
			mortalityRateChartOptions.value.echarts.series[0].data = series_data;
			mortalityRateChartOptions.value.echarts.xAxis.data = x_data;
		});
	};
	//手术患者并发症发生率 函数处理 ( √ )
	const surgeryComplicationRateChartOptionsFunDeal = (data) => {
		surgeryComplicationRateChartOptions.value.data = data.displayPersonInfoDto;
		let x_data = [];
		let series_data = [];
		data.dRGUserInfoRatioDtoList.forEach(item => {
			x_data.push(item.departMenName);
			series_data.push(item.departMenRatio);
		});

		console.log("x_data", x_data)
		console.log("series_data", series_data)

		nextTick(() => {
			surgeryComplicationRateChartOptions.value.echarts.series[0].data = series_data;
			surgeryComplicationRateChartOptions.value.echarts.xAxis.data = x_data;
		});
	};
	// I类切口手术部位感染率 函数处理 ( √ )
	const infectionRateChartOptionsFunDeal = (data) => {
		infectionRateChartOptions.value.data = {
			iSurgicalRatio: data.iSurgicalRatio,
			today_ISurgicalRatio: data.today_ISurgicalRatio,
		};
		let series_data = [{
				value: data.iInfectionCount,
				name: '切口感染',
				itemStyle: {
					color: '#EF4545'
				}
			},
			{
				value: data.surgicalCount,
				name: '正常',
				itemStyle: {
					color: '#10B981'
				}
			}
		];
		nextTick(() => {
			infectionRateChartOptions.value.echarts.series[0].data = series_data;
		});
	};
	// 平均住院日 函数处理 ( √ )
	const averageLengthOfStayChartOptionsFunDeal = (data) => {
		averageLengthOfStayChartOptions.value.data = {
			avgPatientDayRatio: data.avgPatientDayRatio,
			today_AvgPatientDayRatio: data.today_AvgPatientDayRatio
		};
		nextTick(() => {
			averageLengthOfStayChartOptions.value.echarts.series[0].data[0].value = data.today_AvgPatientDayRatio;
		});
	};
	// 重返率 函数处理 ( √ )
	const readmissionRateChartOptionsFunDeal = (data) => {
		readmissionRateChartOptions.value.data = data.displayRestartDto;
		let x_data = [];
		let series_data = [];
		data.displayYearRestartDtoList.forEach(item => {
			x_data.push(item.year + "年" + item.month + "月");
			series_data.push(item.today_RestartRatio);
		});
		nextTick(() => {
			readmissionRateChartOptions.value.echarts.series[0].data = series_data;
			readmissionRateChartOptions.value.echarts.xAxis.data = x_data;
		});
	};
	// 出院患者手术占比 函数处理 ( X  )  todo.... 接口数据不匹配,需要重新对接
	const clinicalPathwayRateChartOptionsFunDeal = (data) => {
		clinicalPathwayRateChartOptions.value.data = data.displayClinicalPathwayDto;
		let x_data = [];
		let series_data = [];
		data.displayDeptClinicalPathwayDtoList.forEach(item => {
			x_data.push(item.year + "年" + item.month + "月");
			series_data.push(item.clinicalPathwayRatio);
		});
		nextTick(() => {
			clinicalPathwayRateChartOptions.value.series[0].data = series_data;
			clinicalPathwayRateChartOptions.value.xAxis.data = x_data;
		});
	};
	// 抗菌药物使用强度 函数处理
	const antibioticUsageIntensityChartOptionsFunDeal = (data) => {
		antibioticUsageIntensityChartOptions.value.data = data.displayANTDrugTakeRatio;
		const uniqueDeparts = [...new Set(data.drugTakeDtoList.map(item => item.personDepartName))]; // 纵轴数据
		const uniqueTimes = [...new Set(data.drugTakeDtoList.map(item => {
			const month = item.month.toString().padStart(2, '0');
			return `${item.year}年${month}月`;
		}))];
		const echartsHeatData = data.drugTakeDtoList.map(item => { // 构建热力图数据
			const departIndex = uniqueDeparts.indexOf(item.personDepartName);
			const timeStr = `${item.year}年${item.month.toString().padStart(2, '0')}月`;
			const timeIndex = uniqueTimes.indexOf(timeStr);
			return [timeIndex, departIndex, item.ntDrugTakeCount]; // 修正：timeIndex 在前，departIndex 在后
		});
		nextTick(() => {
			antibioticUsageIntensityChartOptions.value.echarts.series[0].data = echartsHeatData;
			antibioticUsageIntensityChartOptions.value.echarts.xAxis.data = uniqueTimes;
			antibioticUsageIntensityChartOptions.value.echarts.yAxis.data = uniqueDeparts;
		});
	};
	// 检验和病理阳性率 函数处理  ( X  )  todo.... 接口数据不匹配,需要重新对接
	const criticalValueResponseRateChartOptionsFunDeal = (data) => {
		criticalValueResponseRateChartOptions.value.data = data.displayReportDto;
		let series_data = [{
				value: data.displayReportDto.reportRatio,
				name: '及时处置'
			},
			{
				value: 100 - data.displayReportDto.reportRatio,
				name: '未及时处置'
			}
		];
		nextTick(() => {
			criticalValueResponseRateChartOptions.value.echarts.series[0].data = series_data;
		});
	};
	// 大型设备检查阳性率 函数处理
	const largeEquipmentPositiveRateChartOptionsFunDeal = (data) => {
		largeEquipmentPositiveRateChartOptions.value.data = {
			posSumRatio: data.posSumRatio,
			today_POSSumRatio: data.today_POSSumRatio,
		};
		let series_data = [{
				value: data.today_POSSumRatio,
				name: '阳性',
				itemStyle: {
					color: '#FBBF24' // 橙色
				}
			},
			{
				value: 100 - data.today_POSSumRatio,
				name: '阴性',
				itemStyle: {
					color: '#75b85e' // 深灰（背景色）
				}
			}
		];
		nextTick(() => {
			largeEquipmentPositiveRateChartOptions.value.echarts.series[0].data = series_data;
		});
	};
	// 数据更新-----------------------------------------------------
	const updateDashboardCharts = async () => {
		const results = await Promise.allSettled([ // 并发获取所有数据
			getDisplayLowDeath(),
			getDisplayRelapse(),
			getDisplayISurgical(),
			getDisplayAVGPerson(),
			getDisplayRestart(),
			getDisplayClinical(),
			getDisplayANTDrug(),
			getDisplayReport(),
			getDisplayDevice(),
			getDisplayQuality(),
		]);
		if (results[0].status == 'fulfilled' && results[0].value.data.code == 200) {
			mortalityRateChartOptionsFunDeal(results[0].value.data.data);
		}
		if (results[1].status === 'fulfilled' && results[1].value.data.code == 200) {
			surgeryComplicationRateChartOptionsFunDeal(results[1].value.data.data);
		}
		if (results[2].status === 'fulfilled' && results[2].value.data.code == 200) {
			infectionRateChartOptionsFunDeal(results[2].value.data.data);
		}
		if (results[3].status === 'fulfilled' && results[3].value.data.code == 200) {
			averageLengthOfStayChartOptionsFunDeal(results[3].value.data.data);
		}
		if (results[4].status === 'fulfilled' && results[4].value.data.code == 200) {
			readmissionRateChartOptionsFunDeal(results[4].value.data.data);
		}
		// 出院患者手术占比
		if (results[5].status === 'fulfilled' && results[5].value.data.code == 200) {
			// clinicalPathwayRateChartOptionsFunDeal(results[5].value.data.data);
		}
		if (results[6].status === 'fulfilled' && results[6].value.data.code == 200) {
			antibioticUsageIntensityChartOptionsFunDeal(results[6].value.data.data);
		}
		if (results[7].status === 'fulfilled' && results[7].value.data.code == 200) {
			// criticalValueResponseRateChartOptionsFunDeal(results[7].value.data.data);
		}
		// 在 updateDashboardCharts 函数中添加
		if (results[8].status === 'fulfilled' && results[8].value.data.code == 200) {
			largeEquipmentPositiveRateChartOptionsFunDeal(results[8].value.data.data);
		}

		if (results[9].status === 'fulfilled' && results[9].value.data.code == 200) {
			indicators.value[0].currentRate = results[9].value.data.data.today_SAEEventRatio;
			indicators.value[0].change = results[9].value.data.data.saeEventRatio;
			indicators.value[0].trend = results[9].value.data.data.saeEventRatio >= 0 ? 'up' : 'down';
			indicators.value[0].description = '较上月' + results[9].value.data.data.saeEventRatio + '%，但仍需持续关注用药安全和跌倒预防。';
			indicators.value[1].currentRate = results[9].value.data.data.today_HAIEventRatio;
			indicators.value[1].change = results[9].value.data.data.saeEventRatio;
			indicators.value[1].trend = results[9].value.data.data.saeEventRatio >= 0 ? 'up' : 'down';
			indicators.value[1].description = '较上月' + results[9].value.data.data.saeEventRatio + '%，重点加强ICU和外科手卫生监管。';
			indicators.value[2].currentRate = results[9].value.data.data.today_DeathEventRatio;
			indicators.value[2].change = results[9].value.data.data.deathEventRatio;
			indicators.value[2].trend = results[9].value.data.data.deathEventRatio >= 0 ? 'up' : 'down';
			indicators.value[2].description = '较上月' + results[9].value.data.data.deathEventRatio + '%，继续保持危重患者早期预警系统运行。';
		}
	};
	onMounted(() => {
		updateDashboardCharts();
		// const timer = setInterval(updateDashboardCharts, 5 * 60 * 1000);
		// onUnmounted(() => {
		//   clearInterval(timer);
		// });
	});

	// ===========================  AI部分
	const drawer = ref(false)
	const isStreaming = ref(false);
	const renderedHTML = ref('');
	const outputRef = ref(null);
	const API_KEY = 'sk-69a5314907eb4feea7c1a371c6778a51'
	const API_URL = ref(
		'https://dashscope.aliyuncs.com/api/v2/apps/agent/9c8cdc23a81e48cc9979e9543ac06c4f/compatible-mode/v1/responses');
	const md = new MarkdownIt({
		html: false,
		breaks: true,
		typographer: true
	})

	function detectAndConvertTextTable(text) {
		const lines = text.trim().split('\n')
		let headers = []
		let rows = []

		for (const line of lines) {
			const trimmed = line.trim()
			if (!trimmed) continue

			// 使用多个空格或制表符分割
			const cells = trimmed.split(/\s{2,}|\t/).filter(Boolean)
			if (cells.length < 2) continue // 至少两列

			// 判断是否为表头：不含明显数字/百分比
			const hasNumbers = /[\d\.]+%?/.test(trimmed)
			if (!headers.length && !hasNumbers) {
				headers = cells
			} else if (hasNumbers && cells.length >= headers.length) {
				// 数据行：补全或截断以匹配表头长度
				const row = cells.slice(0, headers.length)
				rows.push(row)
			}
		}

		// 构造 Markdown 表格
		if (headers.length >= 2 && rows.length >= 1) {
			const headerRow = '| ' + headers.join(' | ') + ' |'
			const separatorRow = '| ' + headers.map(() => '---').join(' | ') + ' |'
			const dataRows = rows.map(row => '| ' + row.join(' | ') + ' |').join('\n')
			return [headerRow, separatorRow, dataRows].join('\n')
		}

		return null
	}
	const originalRender = md.render.bind(md)
	md.render = function(content) {
		let enhancedContent = content
		// 查找可能的表格块（连续多行，每行有多个空格）
		const potentialBlocks = enhancedContent.match(/(?:^|\n)(?:[^\n]+\s+[^\n]+\n?)+/g)
		if (potentialBlocks) {
			potentialBlocks.forEach(block => {
				const cleanedBlock = block.trim()
				if (!cleanedBlock || cleanedBlock.startsWith('|') || cleanedBlock.includes('---')) return

				const tableMarkdown = detectAndConvertTextTable(cleanedBlock)
				if (tableMarkdown) {
					enhancedContent = enhancedContent.replace(cleanedBlock, tableMarkdown)
				}
			})
		}
		try {
			return originalRender(enhancedContent)
		} catch (e) {
			console.error('[Markdown] 渲染失败:', e)
			return `<p style="color:red">❌ 内容渲染错误</p>`
		}
	}

	// 内网访问
	const startStreamIntranet = async (requestData) => {
		if (isStreaming.value) return
		renderedHTML.value = ''
		isStreaming.value = true
		let accumulatedText = ''
		try {
			let payload = {
				question: requestData,
				type: 2
			};
			const response = await fetch('http://192.168.0.103:9907/api/Bailian/stream', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify(payload)
			})
			if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`)
			const reader = response.body.getReader()
			const decoder = new TextDecoder('utf-8')
			let buffer = ''
			isAiLoading.value = true
			while (true) {
				const {
					done,
					value
				} = await reader.read()
				if (done) break
				buffer += decoder.decode(value, {
					stream: true
				})
				const lines = buffer.split('\n')
				buffer = lines.pop()
				for (const line of lines) {
					const trimmed = line.trim()
					if (!trimmed.startsWith('data:')) continue

					const dataStr = trimmed.slice(5).trim()
					if (!dataStr || dataStr === '[DONE]') continue

					try {
						if (dataStr.includes('data:')) {
							const data = JSON.parse(dataStr.replace('data:', '').trim())
							if (data.type === 'response.output_text.delta' && typeof data.delta === 'string') {
								const deltaText = data.delta
								accumulatedText += deltaText
								console.log(data.delta)
								// 使用增强版 markdown-it 渲染（含表格修复）
								const unsafeHtml = md.render(accumulatedText)
								renderedHTML.value = DOMPurify.sanitize(unsafeHtml)
								// 自动滚动到底部
								await nextTick()
								outputRef.value?.scrollTo?.(0, outputRef.value.scrollHeight)
							}
						}
					} catch (err) {
						console.warn('[解析失败]', err, dataStr)
					}
				}
			}
			const finalText = accumulatedText + '\n\n✅ 报告生成完成。'
			const unsafeHtml = md.render(finalText)
			renderedHTML.value = DOMPurify.sanitize(unsafeHtml)
		} catch (error) {
			console.error('[请求失败]', error)
			renderedHTML.value = `<span style="color:red">❌ 请求失败：${error.message}</span>`
		} finally {
			isStreaming.value = false
		}
	}

	const startStream = async (requestData) => {
		if (isStreaming.value) return
		renderedHTML.value = ''
		isStreaming.value = true
		let accumulatedText = ''
		try {
			const payload = {
				input: [{
					type: 'message',
					role: 'user',
					content: [{
						type: 'input_text',
						text: requestData
					}]
				}],
				stream: true
			}
			console.log('API_URL :' + API_URL.value)
			console.log('API_KEY :' + API_KEY)
			const response = await fetch(API_URL.value, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
					'Authorization': `Bearer ${API_KEY}`
				},
				body: JSON.stringify(payload)
			})
			if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`)
			const reader = response.body.getReader()
			const decoder = new TextDecoder('utf-8')
			let buffer = ''
			isAiLoading.value = true
			while (true) {
				const {
					done,
					value
				} = await reader.read()
				if (done) break
				buffer += decoder.decode(value, {
					stream: true
				})
				const lines = buffer.split('\n')
				buffer = lines.pop()
				for (const line of lines) {
					const trimmed = line.trim()
					if (!trimmed.startsWith('data:')) continue

					const dataStr = trimmed.slice(5).trim()
					if (!dataStr || dataStr === '[DONE]') continue

					try {
						const data = JSON.parse(dataStr)
						if (data.type === 'response.output_text.delta' && typeof data.delta === 'string') {
							const deltaText = data.delta
							accumulatedText += deltaText
							console.log(data.delta)
							// 使用增强版 markdown-it 渲染（含表格修复）
							const unsafeHtml = md.render(accumulatedText)
							renderedHTML.value = DOMPurify.sanitize(unsafeHtml)
							// 自动滚动到底部
							await nextTick()
							outputRef.value?.scrollTo?.(0, outputRef.value.scrollHeight)
						}
					} catch (err) {
						console.warn('[解析失败]', err, dataStr)
					}
				}
			}
			const finalText = accumulatedText + '\n\n✅ 报告生成完成。'
			const unsafeHtml = md.render(finalText)
			renderedHTML.value = DOMPurify.sanitize(unsafeHtml)
		} catch (error) {
			console.error('[请求失败]', error)
			renderedHTML.value = `<span style="color:red">❌ 请求失败：${error.message}</span>`
		} finally {
			isStreaming.value = false
		}
	}
	const opened = () => {
		isAiLoading.value = false;
		const requestText = `
     低风险组病例死亡率：${mortalityRateChartOptions.value.data.today_LowDeathRatio}%，
     手术患者并发症发生率：${surgeryComplicationRateChartOptions.value.data.today_SurgicalRatio}%，
     1类切口手术部位感染率：${infectionRateChartOptions.value.data.today_ISurgicalRatio}%，
     平均住院日：${averageLengthOfStayChartOptions.value.data.today_AvgPatientDayRatio}天，
     重返率：${readmissionRateChartOptions.value.data.today_RestartRatio}%，
     出院患者手术占比：${0}%，
     抗菌药物使用强度：${antibioticUsageIntensityChartOptions.value.data.today_ANTDrugTakeRatio} DDDs，
     检验和病理阳性率：${criticalValueResponseRateChartOptions.value.data.today_ReportRatio}%，
     大型设备检查阳性率：${largeEquipmentPositiveRateChartOptions.value.data.today_POSSumRatio}%，
     全院医疗质量安全不良事件（AE）发生率：${indicators.value[0].currentRate}%，
     全院医院感染（HAI）发生率：${indicators.value[1].currentRate}%，
     全院住院患者死亡率：${indicators.value[2].currentRate}%。`;

		// 外网
		startStream(requestText)
		// 内网
		// startStreamIntranet(requestText)
	}
</script>
<style scoped lang="less">
	.dashboard-container {
		width: 100%;
		height: 100%;
		background-color: #0F172AFF;
		font-family: 'Microsoft YaHei', sans-serif;
		color: var(--text-color);
		padding: 10px 20px;
		box-sizing: border-box;

		.dashboard-header {
			padding: 10px 0;

			.logo {
				width: 60px;
				height: 60px;
				border-radius: 50%;
			}

			.title-box {
				margin-left: 20px;

				.title {
					font-size: 21px;
					font-weight: bolder;
				}

				.hospital-name {
					font-size: 14px;
					padding-top: 5px;
					color: #818999;
				}
			}

			.right-box {
				.time-box {
					margin-right: 20px;

					.current-time-label {
						font-size: 12px;
						color: #818999;
					}

					.current-time-value {
						font-size: 18px;
						padding-top: 5px;
						font-weight: bolder;
					}

				}

				.avatar {
					width: 50px;
					height: 50px;
					border-radius: 50%;
					margin: 0 auto;
					display: block;
				}

				.user-name {
					font-size: 12px;
					padding-top: 5px;
					color: #818999;
				}
			}
		}

		.dashboard-main {
			margin-top: 5px;

			.left-wrapper {
				.indicator-container {
					display: flex;
					flex-wrap: wrap;
					gap: 10px;
					margin-top: 5px;

					.indicator-item {
						display: flex;
						align-items: flex-start;
						gap: 10px;
						padding: 15px;
						background-color: #0F172A;
						border-radius: 8px;
						flex: 1;
						min-width: 300px;

						.indicator-icon {
							width: 40px;
							height: 40px;
							border-radius: 50%;
							object-fit: cover;
						}

						.indicator-content {
							flex: 1;

							.indicator-title {
								font-size: 16px;
								color: #fff;
								margin-bottom: 5px;
							}

							.indicator-rate {
								display: flex;
								align-items: center;
								gap: 5px;

								.current-rate {
									font-size: 14px;
									color: #94979e;
									padding-top: 3px;
								}

								.change {
									font-size: 14px;
									padding: 0 6px;
									border-radius: 4px;

									&.up {
										color: #f56c6c;
										background-color: rgba(245, 108, 108, 0.2);
									}

									&.down {
										color: #12ec2f;
										background-color: rgba(64, 158, 254, 0.2);
									}
								}
							}

							.indicator-desc {
								padding-top: 3px;
								font-size: 15px;
								color: #94979e;
							}
						}
					}
				}
			}

			.right-wrapper {
				background-color: #15272A;
				border-radius: 15px;
				border: 2px solid #0F3338;
				padding: 20px;

				// 实时预警
				.alert-item {
					padding: 14px;
					background-color: rgba(255, 255, 255, 0.08);
					border-radius: 6px;
					margin-top:20px;
					border-left: 4px solid #F56C6CFF;

					&.high-risk {
						border-left-color: #F56C6CFF;
					}

					&.critical {
						border-left-color: #E6A23CFF;
					}

					.alert-title {
						font-size: 16px;
						color: #fff;
						margin-bottom: 10px;
					}

					.alert-time {
						font-size: 14px;
						color: #ccc;
						margin-bottom: 10px;
					}

					.alert-content {
						font-size: 14px;
						color: #ddd;

					}

				}

				// 质控目标
				.target-item {
					margin-top: 15px;

					.target-label {
						font-size: 14px;
						color: #fff;
						margin-bottom: 5px;
					}

					.target-value {
						font-size: 14px;
						color: #94979e;
					}

					.progress-bar {
						height: 8px;
						background-color: rgba(255, 255, 255, 0.1);
						border-radius: 4px;
						overflow: hidden;

						.progress-bg {
							position: relative;
							width: 100%;
							height: 100%;
							background-color: rgba(255, 255, 255, 0.1);
						}

						.progress {
							height: 100%;
							border-radius: 4px;
							transition: width 0.3s ease;
						}
					}
				}

				.ai-section {
					margin-top: 10px;

					&.root-cause {
						border-left: 4px solid #F56C6CFF;
					}

					&.optimization {
						border-left: 4px solid #E6A23CFF;
					}

					&.prediction {
						border-left: 4px solid #409EFFFF;
					}

					// AI建议
					.ai-item {
						margin-top: 10px;
						padding: 16px;
						background-color: rgba(255, 255, 255, 0.08);
						border-radius: 6px;
						border-left: 4px solid #F56C6CFF;

						.ai-title {
							font-size: 15px;
							color: #fff;
							margin-bottom: 10px;
						}

						.ai-desc {
							font-size: 14px;
							color: #ccc;
							margin-bottom: 8px;
							line-height: 1.4;
						}

						.ai-suggestion {
							font-size: 13px;
							color: #94979e;
							padding-left: 5px;
							line-height: 1.4;
						}
					}
				}
			}

		}
	}

	// ================================
	::v-deep(.el-drawer) {
		background-color: rgba(12, 16, 19, 0.91);
	}

	::v-deep(.el-drawer__body) {
		padding: 0px
	}

	.response-box {
		width: 100%;
		padding: 16px;
		overflow-y: auto;
		line-height: 1.7;
		font-size: 15px;
		background-color: #ffffff;
		color: #333333;
	}

	/* ==================== 富文本样式 ==================== */
	.ai-response-content h1,
	.ai-response-content h2,
	.ai-response-content h3 {
		margin: 1em 0 0.5em;
		color: #07173b;
	}

	.ai-response-content h1 {
		font-size: 1.8em;
		text-align: center;
	}

	.ai-response-content h2 {
		font-size: 1.5em;
		border-left: 4px solid #007bff;
		padding-left: 12px;
	}

	.ai-response-content h3 {
		font-size: 1.3em;
		color: #34495e;
	}

	:global(.ai-response-content table) {
		width: 100%;
		border-collapse: collapse;
		margin: 1em 0;
		font-size: 0.95em;
		border: 1px solid #2c2a2a;
	}

	:global(.ai-response-content th,
		.ai-response-content td) {
		border: 1px solid #ccc;
		padding: 8px 12px;
		text-align: center;
	}

	:global(.ai-response-content th) {
		background-color: #f0f5ff;
		font-weight: 600;
		color: #1a3b6d;
	}

	:global(.ai-response-content tr:nth-child(even)) {
		background-color: #f9f9f9;
	}

	:global(.ai-response-content p) {
		margin: 0.6em 2;
	}

	:global(.ai-response-content ul) {
		margin-left: 40px;
		margin: 0.6em 1;
		padding-left: 1;
	}

	:global(.ai-response-content ol) {
		margin-left: 40px;
		margin: 0.6em 2;
		padding-left: 2;
	}

	:global(.ai-response-content li) {
		margin: 0.6em 1.2;
		padding-left: 20px;
	}

	.cursor {
		animation: blink 1.2s step-end infinite;
		color: #007bff;
		font-weight: bold;
		font-size: 1.1em;
	}

	:global(.ai-message table) {
		width: 100%;
		border-collapse: collapse;
		margin: 1em 0;
		font-size: 0.95em;
	}

	:global(.ai-message th,
		.ai-message td) {
		border: 1px solid #ccc;
		padding: 6px 10px;
		text-align: left;
	}

	:global(.ai-message th) {
		background-color: #f0f5ff;
		font-weight: 600;
	}

	:global(.ai-message tr:nth-child(even)) {
		background-color: #f9f9f9;
	}

	@keyframes blink {

		0%,
		100% {
			opacity: 1;
		}

		50% {
			opacity: 0;
		}
	}
</style>